package com.power.sifa.correction.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.google.common.base.Throwables;
import com.plf.common.domain.YesNo;
import com.plf.core.base.model.EnumerationHelper;
import com.plf.core.base.model.Ha_depart;
import com.plf.core.base.service.Ha_departService;
import com.power.sifa.aop.service.SMService;
import com.power.sifa.correction.model.Crc_person;
import com.power.sifa.correction.model.pojo.bo.Crc_personExcelBO;
import com.power.sifa.correction.service.Crc_personService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @ClassName Crc_personListener
 * @Author xiongzw
 * @Date 2023/12/6 16:34
 * @Description excel导入服务
 * @Version: 1.0
 **/


@Slf4j
public class Crc_personListener extends AnalysisEventListener<Crc_personExcelBO> {


    /**
     * 当前的区划信息
     */
    private static final ThreadLocal<List<Ha_depart>> departLocal = new ThreadLocal<>();


    /**
     * 每次保存的数据量
     */
    private static final int INSERT_SIZE = 100;

    /**
     * crc_personService
     */
    private final Crc_personService crc_personService;

    /**
     * 缓存的数据列
     */
    private List<Crc_person> cacheList = ListUtils.newArrayListWithExpectedSize(INSERT_SIZE);

    private final SMService smService;

    public Crc_personListener(Crc_personService crc_personService, SMService smService) {
        this.crc_personService = crc_personService;
        this.smService = smService;
    }

    /**
     * 性别转换
     *
     * @param crc_person
     * @param genderText
     */
    public void transGender(Crc_person crc_person, String genderText) {
        // 默认为null
        crc_person.setGender(null);
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> genderEnum = helper.getEnumerationValues("Tp_gender");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(genderText) && CollectionUtil.isNotEmpty(genderEnum)) {
            Integer genderVal = null;
            for (Map<String, Object> gender : genderEnum) {
                if (gender.containsKey("description") && gender.get("description").equals(genderText)) {
                    genderVal = (Integer) gender.get("id");
                    crc_person.setGender(genderVal);
                }
            }
        }
    }

    /**
     * 矫正类别转换
     *
     * @param crc_person
     * @param crctype
     */
    public void transCrctype(Crc_person crc_person, String crctype) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> crctypeEnum = helper.getEnumerationValues("Tp_crc_user");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(crctype) && CollectionUtil.isNotEmpty(crctypeEnum)) {
            Integer crcVal = null;
            for (Map<String, Object> crctypeMap : crctypeEnum) {
                if (crctypeMap.containsKey("description") && crctypeMap.get("description").equals(crctype)) {
                    crcVal = (Integer) crctypeMap.get("id");
                    crc_person.setCrctype(crcVal);
                }
            }
        }
    }


    /**
     * 进行民族的转换
     *
     * @param crc_person
     * @param nation
     */
    public void transNationType(Crc_person crc_person, String nation) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> nationEnum = helper.getEnumerationValues("Tp_nation");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(nation) && CollectionUtil.isNotEmpty(nationEnum)) {
            Integer nationVal = null;
            for (Map<String, Object> nationMap : nationEnum) {
                if (nationMap.containsKey("description") && nationMap.get("description").equals(nation)) {
                    nationVal = (Integer) nationMap.get("id");
                    crc_person.setNation(nationVal);
                }
            }
        }
    }

    /**
     * 转换文化程度文本
     *
     * @param crc_person
     * @param culture
     */
    public void transCulture(Crc_person crc_person, String culture) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> cultureEnum = helper.getEnumerationValues("Per_edu");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(culture) && CollectionUtil.isNotEmpty(cultureEnum)) {
            Integer cultureVal = null;
            for (Map<String, Object> cultureMap : cultureEnum) {
                if (cultureMap.containsKey("description") && cultureMap.get("description").equals(culture)) {
                    cultureVal = (Integer) cultureMap.get("id");
                    crc_person.setCulture(cultureVal);
                }
            }
        }
    }

    /**
     * 进行国籍的转换
     *
     * @param crc_person
     * @param nationality
     */
    public void transNationality(Crc_person crc_person, String nationality) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> nationalityEnum = helper.getEnumerationValues("Per_nationality");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(nationality) && CollectionUtil.isNotEmpty(nationalityEnum)) {
            Integer nationalityVal = null;
            for (Map<String, Object> nationalityMap : nationalityEnum) {
                if (nationalityMap.containsKey("description") && nationalityMap.get("description").equals(nationality)) {
                    nationalityVal = (Integer) nationalityMap.get("id");
                    crc_person.setNationality(nationalityVal);
                }
            }
        }
    }

    /**
     * 进行户口的转换
     *
     * @param crc_person
     * @param houseType
     */
    public void transHouseType(Crc_person crc_person, String houseType) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> houseTypeEnum = helper.getEnumerationValues("Per_housetype");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(houseType) && CollectionUtil.isNotEmpty(houseTypeEnum)) {
            Integer houseTypeVal = null;
            for (Map<String, Object> houseTypeMap : houseTypeEnum) {
                if (houseTypeMap.containsKey("description") && houseTypeMap.get("description").equals(houseType)) {
                    houseTypeVal = (Integer) houseTypeMap.get("id");
                    crc_person.setHousetype(houseTypeVal);
                }
            }
        }
    }

    /**
     * 进行就业就学的转换
     *
     * @param crc_person
     * @param perform
     */
    public void transPerform(Crc_person crc_person, String perform) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> performEnum = helper.getEnumerationValues("Per_perform");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(perform) && CollectionUtil.isNotEmpty(performEnum)) {
            Integer performVal = null;
            for (Map<String, Object> performMap : performEnum) {
                if (performMap.containsKey("description") && performMap.get("description").equals(perform)) {
                    performVal = (Integer) performMap.get("id");
                    crc_person.setPerform(performVal);
                }
            }
        }
    }

    /**
     * 进行政治面貌转换
     *
     * @param crc_person
     * @param politics
     */
    public void transPolitics(Crc_person crc_person, String politics) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> politicsEnum = helper.getEnumerationValues("Per_politics");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(politics) && CollectionUtil.isNotEmpty(politicsEnum)) {
            Integer politicsVal = null;
            for (Map<String, Object> politicsMap : politicsEnum) {
                if (politicsMap.containsKey("description") && politicsMap.get("description").equals(politics)) {
                    politicsVal = (Integer) politicsMap.get("id");
                    crc_person.setPolitics(politicsVal);
                }
            }
        }
    }

    /**
     * 进行婚姻状况的转换
     *
     * @param crc_person
     * @param marriage
     */
    public void transMarriage(Crc_person crc_person, String marriage) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> marriageEnum = helper.getEnumerationValues("Per_marry");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(marriage) && CollectionUtil.isNotEmpty(marriageEnum)) {
            Integer marriageVal = null;
            for (Map<String, Object> marriageMap : marriageEnum) {
                if (marriageMap.containsKey("description") && marriageMap.get("description").equals(marriage)) {
                    marriageVal = (Integer) marriageMap.get("id");
                    crc_person.setMarriage(marriageVal);
                }
            }
        }
    }


    /**
     * 进行刑法的转换
     *
     * @param crc_person
     * @param penalty
     */
    public void transPenalty(Crc_person crc_person, String penalty) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> penaltyEnum = helper.getEnumerationValues("Tp_crc_penalty");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(penalty) && CollectionUtil.isNotEmpty(penaltyEnum)) {
            Integer penaltyVal = null;
            for (Map<String, Object> penaltyMap : penaltyEnum) {
                if (penaltyMap.containsKey("description") && penaltyMap.get("description").equals(penalty)) {
                    penaltyVal = (Integer) penaltyMap.get("id");
                    crc_person.setPenalty(penaltyVal);
                }
            }
        }
    }

    /**
     * 入矫类别的转换
     *
     * @param crc_person
     * @param entertype
     */
    public void transEntertype(Crc_person crc_person, String entertype) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> entertypeEnum = helper.getEnumerationValues("Tp_crc_enter");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(entertype) && CollectionUtil.isNotEmpty(entertypeEnum)) {
            Integer entertypeVal = null;
            for (Map<String, Object> entertypeMap : entertypeEnum) {
                if (entertypeMap.containsKey("description") && entertypeMap.get("description").equals(entertype)) {
                    entertypeVal = (Integer) entertypeMap.get("id");
                    crc_person.setEntertype(entertypeVal);
                }
            }
        }
    }

    public void transOrgantype(Crc_person crc_person, String organtype) {
        EnumerationHelper helper = SpringUtil.getBean(EnumerationHelper.class);
        List<Map<String, Object>> organtypeEnum = helper.getEnumerationValues("Tp_organtype");
        if (ObjectUtil.isNotNull(crc_person) && StringUtils.isNotEmpty(organtype) && CollectionUtil.isNotEmpty(organtypeEnum)) {
            Integer organtypeVal = null;
            for (Map<String, Object> organtypeMap : organtypeEnum) {
                if (organtypeMap.containsKey("description") && organtypeMap.get("description").equals(organtype)) {
                    organtypeVal = (Integer) organtypeMap.get("id");
                    crc_person.setOrgantype(organtypeVal);
                }
            }
        }
    }

    /**
     * 进行行政区县和所属司法所的转换
     *
     * @param crc_person
     * @param departName
     */
    public void transDepart(Crc_person crc_person, String departName) {
        Ha_departService ha_departService = SpringUtil.getBean(Ha_departService.class);
        List<Ha_depart> departList = departLocal.get();
        if (CollectionUtil.isEmpty(departList)) {
            departList = ha_departService.findAll();
            departLocal.set(departList);
        }
        if (CollectionUtil.isNotEmpty(departList)) {
            Ha_depart depart = departList.stream().filter(el -> el.getName().equals(departName)).findAny().orElse(null);
            if (ObjectUtil.isNotNull(depart)) {
                crc_person.setDeptid(depart.getId());
                crc_person.setAdid(ObjectUtil.isNotNull(depart.getAdid()) && depart.getAdid().length() > 6
                        ? depart.getAdid().substring(0, 6) : null);
            }
        }
    }


    @Override
    public void invoke(Crc_personExcelBO personExcelBO, AnalysisContext analysisContext) {
        // 校验数据
        try {
            if (ObjectUtil.isNotNull(personExcelBO)) {

                Crc_person crc_person = new Crc_person(personExcelBO);
                // 身份证加密
                if (StringUtils.isNotBlank(personExcelBO.getCardno()) && personExcelBO.getCardno().length() == 18) {
                    crc_person.setCardnoIndex(personExcelBO.getCardno().substring(personExcelBO.getCardno().length() - 4));
                    crc_person.setCardno(smService.encrypt(personExcelBO.getCardno()));
                }
                // 进行性别和矫正类型的转换
                if (StringUtils.isNotBlank(personExcelBO.getGender())) {
                    transGender(crc_person, personExcelBO.getGender());
                }
                // 进行民族的转换
                if (StringUtils.isNotBlank(personExcelBO.getNation())) {
                    transNationType(crc_person, personExcelBO.getNation());
                }
                // 进行文化程度转换
                if (StringUtils.isNotBlank(personExcelBO.getCulture())) {
                    transCulture(crc_person, personExcelBO.getCulture());
                }
                // 进行矫正类别的转换
                if (StringUtils.isNotBlank(personExcelBO.getCrctype())) {
                    transCrctype(crc_person, personExcelBO.getCrctype());
                }
                // 进行国籍转换
                if (StringUtils.isNotBlank(personExcelBO.getNationality())) {
                    transNationality(crc_person, personExcelBO.getNationality());
                }
                // 进行户口类型的转换
                if (StringUtils.isNotBlank(personExcelBO.getHousetype())) {
                    transHouseType(crc_person, personExcelBO.getHousetype());
                }
                // 进行就业就学的转换
                if (StringUtils.isNotBlank(personExcelBO.getPerform())) {
                    transPerform(crc_person, personExcelBO.getPerform());
                }
                // 进行政治面貌
                if (StringUtils.isNotBlank(personExcelBO.getPolitics())) {
                    transPolitics(crc_person, personExcelBO.getPolitics());
                }
                // 进行是否结婚转换
                if (StringUtils.isNotBlank(personExcelBO.getMarriage())) {
                    transMarriage(crc_person, personExcelBO.getMarriage());
                }
                // 进行是否有传染史文本的转换
                if (StringUtils.isNotBlank(personExcelBO.getIsinfect())) {
                    if (personExcelBO.getIsinfect().contains("是")) {
                        crc_person.setIsinfect(YesNo.YES);
                    } else if (personExcelBO.getIsinfect().contains("否")) {
                        crc_person.setIsinfect(YesNo.NO);
                    }
                }
                // 进行刑种的转换
                if (StringUtils.isNotBlank(personExcelBO.getPenalty())) {
                    transPenalty(crc_person, personExcelBO.getPenalty());
                }
                // 进行入矫类型的转换
                if (StringUtils.isNotBlank(personExcelBO.getEntertype())) {
                    transEntertype(crc_person, personExcelBO.getEntertype());
                }
                // 进行决定机关类型转换
                if (StringUtils.isNotBlank(personExcelBO.getOrgantype())) {
                    transOrgantype(crc_person, personExcelBO.getOrgantype());
                }
                // 进行行政区县和所属司法所的转换
                if (StringUtils.isNotBlank(personExcelBO.getDeptid())) {
                    transDepart(crc_person, personExcelBO.getDeptid());
                }
                cacheList.add(crc_person);
            }
            // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
            if (cacheList.size() >= INSERT_SIZE) {
                saveData();
                // 存储完成清理 list
                cacheList = ListUtils.newArrayListWithExpectedSize(INSERT_SIZE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }


    private void saveData() {
        try {
            crc_personService.batchSaveOrUpdate(cacheList);
        } catch (Exception e) {
            log.error("社矫人员保存失败：{}", Throwables.getStackTraceAsString(e));
            throw e;
        }

    }
}
